<template>
    <el-dialog :title="title" v-model="visible">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
            <el-form-item label="博文标题" prop="title">
                <el-col :span="24">
                    <el-input clearable v-model="form.title" placeholder="请输入博文标题" />
                </el-col>
            </el-form-item>

            <el-form-item label="博文类型" prop="category_id">
                <el-select v-model="form.category_id" placeholder="请选择分类" @change="getTagList">
                    <el-option
                        v-for="item in categoryOption"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id"
                        :disabled="item.disabled"
                    >
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="摘要" prop="summary">
                <el-col :span="24">
                    <el-input v-model="form.summary" type="textarea" autosize />
                </el-col>
            </el-form-item>

            <el-form-item label="标图" prop="image_url">
                <Uploader
                    v-model="form.image_url"
                    :on-success="thumbUpload"
                    :on-remove="removeThumbUpload"
                />
            </el-form-item>

            <el-form-item label="内容" prop="content">
                <el-col :span="24">
                    <Tinymce v-model="form.content" :config="{ height: 600 }" />
                </el-col>
            </el-form-item>

            <el-form-item label="标签" prop="tag_ids">
                <el-popover placement="right" :width="400" trigger="click">
                    <el-checkbox
                        v-model="checkAll"
                        :indeterminate="isIndeterminate"
                        @change="handleCheckAllChange"
                    >
                        全选
                    </el-checkbox>

                    <el-checkbox-group v-model="form.tag_ids" @change="handleCheckedCitiesChange">
                        <el-checkbox v-for="item in tagList" :key="item.id" :label="item.id">
                            {{ item.title }}
                        </el-checkbox>
                    </el-checkbox-group>

                    <template #reference>
                        <el-button>
                            <el-icon><plus /></el-icon>
                        </el-button>
                    </template>
                </el-popover>
            </el-form-item>

            <el-form-item label="">
                <div class="el-form-tag">
                    <el-tag v-for="item in selectTags" :key="item.id">
                        {{ item.title }}
                    </el-tag>
                </div>
            </el-form-item>

            <el-form-item label="推荐" prop="support">
                <el-switch v-model="form.support"></el-switch>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="visible = false"> 取 消 </el-button>
            <el-button type="warning" :loading="loading" @click="onSubmit(2)"> 草稿箱 </el-button>
            <el-button type="primary" :loading="loading" @click="onSubmit(1)"> 发 布 </el-button>
        </template>
    </el-dialog>
</template>

<script>
import { getCurrentInstance, ref, reactive, watch } from 'vue';
import { adminArticle as Api } from 'api';
import tinymce from '../../../components/tinymce/tinymce.vue';

export default {
    components: { tinymce },
    emits: ['eventUpdate'],
    setup(props, context) {
        const { proxy } = getCurrentInstance();

        let id = ref(null);
        let loading = ref(false); //等待按钮
        let visible = ref(false); //弹窗开关
        let title = ref(null); // 标题

        let categoryOption = ref([]); // 分类

        // 标签
        let checkAll = ref(true); // 标签选择弹窗开关
        let isIndeterminate = ref(true);
        let tagList = ref([]); // 标签列表
        let selectTags = ref([]); // 选中的标签
        // 表单
        let form = reactive({
            title: '',
            category_id: '',
            summary: '',
            support: 0,
            image_url: '',
            content: '',
            tag_ids: [] // 选中的标签ID组
        });
        // 验证
        let rules = {
            title: [{ required: true, message: '请填写文章标题' }],
            category_id: [{ required: true, message: '请选择分类' }],
            summary: [{ required: true, message: '请填写摘要' }],
            content: [{ required: true, message: '请输入内容' }],
            tag_ids: [{ required: true, message: '请勾选标签' }]
        };

        // 初始化
        const init = () => {
            title.value = id.value ? '编辑' : '新增';
            getCategoryList();

            if (id.value) {
                getById();
            }
        };
        // 获取分类列表
        const getCategoryList = async () => {
            const { code, data } = await proxy.$http.get(Api.articleCategory);
            if (code === 200) {
                categoryOption.value = data.list;
            }
        };
        // 获取标签列表
        const getTagList = async () => {
            const { code, data } = await proxy.$http.get(Api.articleTag, {
                params: {
                    category_id: form.category_id
                }
            });

            if (code === 200) {
                tagList.value = data.tags;
            }

            handleCheckedCitiesChange();
        };
        // 获取详情
        const getById = async () => {
            const { code, data } = await proxy.$http.get(Api.getById, {
                params: { id: id.value }
            });

            if (code === 200) {
                let tag_ids = [];
                if (data.list.tag_ids) {
                    let ids = data.list.tag_ids.split(',');
                    for (let i in ids) {
                        tag_ids.push(Number(ids[i]));
                    }
                }

                form.title = data.list.title;
                form.category_id = data.list.category_id;
                form.summary = data.list.summary;
                form.support = data.list.support == 1 ? true : false;
                form.image_url = data.list.image_url;
                form.content = data.list.content;
                form.tag_ids = tag_ids;

                getTagList();
            }
        };
        // 图标上传
        const thumbUpload = (fileStr) => {
            form.image_url = fileStr;
        };
        // 删除图标
        const removeThumbUpload = (fileStr) => {
            form.image_url = fileStr;
        };

        // 标签全选
        const handleCheckAllChange = (val) => {
            let ids = tagList.value.map((v) => v.id);
            form.tag_ids = val ? ids : [];
            selectTags.value = val ? tagList.value : [];
            isIndeterminate.value = false;
        };
        // 标签单个选择
        const handleCheckedCitiesChange = () => {
            let tags = [];
            tagList.value.forEach((item) => {
                let checked = form.tag_ids.some((v) => v == item.id);

                if (checked) tags.push(item);
            });

            form.tag_ids = tags.map((v) => v.id);
            selectTags.value = tags;
        };

        // 表单提交
        const onSubmit = async (status) => {
            await proxy.$refs['formRef'].validate((valid) => {
                if (valid) {
                    loading.value = true;
                }
            });

            if (loading.value) {
                let url = id.value ? Api.update : Api.add;
                let params = {
                    title: form.title,
                    status: status,
                    category_id: form.category_id,
                    summary: form.summary,
                    support: form.support,
                    image_url: form.image_url,
                    content: form.content,
                    tag_ids: form.tag_ids
                };

                if (id.value) params.id = id.value;

                const { code, msg, data } = await proxy.$http.post(url, params);

                if (code === 200) {
                    proxy.$msg.success(msg);

                    context.emit('eventUpdate');
                    visible.value = false;
                } else {
                    proxy.$msg.error(msg ? msg : data);
                }

                loading.value = false;
            }
        };

        // 重置表单
        const resetForm = () => {
            categoryOption.value = [];
            selectTags.value = [];
            tagList.value = [];
            proxy.$refs['formRef'].resetFields();
        };

        // 监听弹窗开关
        watch(visible, (newVal, oldVal) => {
            newVal ? init() : resetForm();
        });

        return {
            id,
            loading,
            visible,
            title,
            categoryOption,
            checkAll,
            isIndeterminate,
            tagList,
            selectTags,
            handleCheckAllChange,
            handleCheckedCitiesChange,
            form,
            rules,
            getTagList,
            thumbUpload,
            removeThumbUpload,
            onSubmit
        };
    }
};
</script>

<style lang="less" scoped>
.el-form-tag span {
    margin-right: 5px;
}
</style>
